package ${projectDomain}.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.unswift.annotation.api.Api;
import com.unswift.annotation.api.ApiField;
import com.unswift.annotation.api.ApiMethod;
import ${projectDomain}.adapter.system.SystemDepartmentAdapter;
import ${projectDomain}.adapter.system.SystemDepartmentJobAdapter;
import ${projectDomain}.adapter.system.SystemDepartmentJobUserAdapter;
import ${projectDomain}.adapter.system.SystemDepartmentUserAdapter;
import ${projectDomain}.adapter.system.SystemRoleAdapter;
import ${projectDomain}.adapter.system.SystemUserAccountAdapter;
import ${projectDomain}.adapter.system.SystemUserAdapter;
import ${projectDomain}.adapter.system.SystemUserRoleAdapter;
import ${projectDomain}.adapter.validate.IValidateAdapter;
import ${projectDomain}.annotation.logger.OperatorLogger;
import ${projectDomain}.core.entity.TokenUser;
import ${projectDomain}.enums.OperatorTypeEnum;
import ${projectDomain}.enums.system.role.AuthorityTypeEnum;
import ${projectDomain}.enums.tree.TreeIconEnum;
import ${projectDomain}.feign.AttachFeign;
import ${projectDomain}.pojo.bo.system.department.SystemDepartmentUserPageBo;
import ${projectDomain}.pojo.bo.system.user.SystemUserAuthorizeRoleListBo;
import ${projectDomain}.pojo.bo.system.user.SystemUserCreateBo;
import ${projectDomain}.pojo.bo.system.user.SystemUserDeleteBo;
import ${projectDomain}.pojo.bo.system.user.SystemUserDepartmentJobTreeBo;
import ${projectDomain}.pojo.bo.system.user.SystemUserPageBo;
import ${projectDomain}.pojo.bo.system.user.SystemUserUpdateBo;
import ${projectDomain}.pojo.bo.system.user.SystemUserUpdateStatusBo;
import ${projectDomain}.pojo.bo.system.user.SystemUserViewBo;
import ${projectDomain}.pojo.bo.system.user.role.SystemUserRoleUpdateBo;
import ${projectDomain}.pojo.bo.system.user.role.SystemUserRoleUpdateListBo;
import ${projectDomain}.pojo.dao.sql.Sql;
import ${projectDomain}.pojo.dao.system.department.SystemDepartmentDataDo;
import ${projectDomain}.pojo.dao.system.department.SystemDepartmentSearchDo;
import ${projectDomain}.pojo.dao.system.department.job.SystemDepartmentJobDataDo;
import ${projectDomain}.pojo.dao.system.department.job.SystemDepartmentJobSearchDo;
import ${projectDomain}.pojo.dao.system.department.job.user.SystemDepartmentJobUserInsertDo;
import ${projectDomain}.pojo.dao.system.department.user.SystemDepartmentUserInsertDo;
import ${projectDomain}.pojo.dao.system.role.SystemRoleDataDo;
import ${projectDomain}.pojo.dao.system.role.SystemRoleSearchDo;
import ${projectDomain}.pojo.dao.system.user.SystemUserDataDo;
import ${projectDomain}.pojo.dao.system.user.SystemUserDeleteDo;
import ${projectDomain}.pojo.dao.system.user.SystemUserInsertDo;
import ${projectDomain}.pojo.dao.system.user.SystemUserPageDo;
import ${projectDomain}.pojo.dao.system.user.SystemUserSingleDo;
import ${projectDomain}.pojo.dao.system.user.SystemUserUpdateDo;
import ${projectDomain}.pojo.dao.system.user.account.SystemUserAccountInsertDo;
import ${projectDomain}.pojo.dao.system.user.role.SystemUserRoleDataDo;
import ${projectDomain}.pojo.dao.system.user.role.SystemUserRoleInsertBatchDo;
import ${projectDomain}.pojo.dao.system.user.role.SystemUserRoleInsertBatchItemDo;
import ${projectDomain}.pojo.vo.page.PageVo;
import ${projectDomain}.pojo.vo.page.PageVo.PageRowHandler;
import ${projectDomain}.pojo.vo.system.department.SystemDepartmentUserPageVo;
import ${projectDomain}.pojo.vo.system.user.SystemUserAuthorizeRoleListVo;
import ${projectDomain}.pojo.vo.system.user.SystemUserAuthorizeRoleVo;
import ${projectDomain}.pojo.vo.system.user.SystemUserCreateVo;
import ${projectDomain}.pojo.vo.system.user.SystemUserDeleteVo;
import ${projectDomain}.pojo.vo.system.user.SystemUserDepartmentJobTreeVo;
import ${projectDomain}.pojo.vo.system.user.SystemUserPageVo;
import ${projectDomain}.pojo.vo.system.user.SystemUserUpdateStatusVo;
import ${projectDomain}.pojo.vo.system.user.SystemUserUpdateVo;
import ${projectDomain}.pojo.vo.system.user.SystemUserViewVo;
import ${projectDomain}.pojo.vo.system.user.role.SystemUserRoleUpdateVo;
import ${projectDomain}.sql.system.user.SystemUserSql;
import ${projectDomain}.utils.LoggerUtils;
import com.unswift.utils.EncryptionUtils;
import com.unswift.utils.ExceptionUtils;
import com.unswift.utils.JsonUtils;
import com.unswift.utils.ObjectUtils;
import com.unswift.utils.StringUtils;

@Service
@Api(value="会员服务", author="liyunlong", date="2023-09-28", version="1.0.0")
public class SystemUserService extends BaseService{
	
	@Autowired
	@ApiField("会员公共服务")
	private SystemUserAdapter systemUserAdapter;
	@Autowired
	@ApiField("会员公共sql")
	private SystemUserSql systemUserSql;
	@Autowired
	@ApiField("会员账号公共服务")
	private SystemUserAccountAdapter systemUserAccountAdapter;
	@Autowired
	@ApiField("会员账号公共服务")
	private SystemUserRoleAdapter systemUserRoleAdapter;
	@Autowired
	@ApiField("角色公共服务")
	private SystemRoleAdapter systemRoleAdapter;
	@Autowired
	@ApiField("部门公共服务")
	private SystemDepartmentAdapter systemDepartmentAdapter;
	@Autowired
	@ApiField("部门职位公共服务")
	private SystemDepartmentJobAdapter systemDepartmentJobAdapter;
	@Autowired
	@ApiField("部门用户公共服务")
	private SystemDepartmentUserAdapter systemDepartmentUserAdapter;
	@Autowired
	@ApiField("部门职位用户公共服务")
	private SystemDepartmentJobUserAdapter systemDepartmentJobUserAdapter;
	@Autowired
	@ApiField("附件feign服务")
	private AttachFeign attachFeign;
	@Autowired
	@ApiField("数据验证业务对象")
	protected IValidateAdapter validateAdapter;
	
	@ApiMethod(value="查询会员分页数据", params=@ApiField("分页对象，包含分页信息及查询条件"), returns=@ApiField("包含查询数据的分页对象"))
	public PageVo<SystemUserPageVo> findPageList(SystemUserPageBo searchBo){
		SystemUserPageDo search=this.convertPojo(searchBo, SystemUserPageDo.class);//将Bo转换为Do
		search.setFirstSize((search.getCurrPage()-1)*search.getPageSize());
		systemUserAdapter.addSelectColumn(search, systemUserSql.findAccountSql(), "account");
		systemUserAdapter.addSelectColumn(search, systemUserSql.findPhoneSql(), "phone");
		systemUserAdapter.addSelectColumn(search, systemUserSql.findEmailSql(), "email");
		systemUserAdapter.addSelectColumn(search, systemUserSql.findRoleNamesSql(), "roleNames");
		if(ObjectUtils.isNotEmpty(searchBo.getAccount())){
			systemUserAdapter.addWhereIn(search, "t.id_", Sql.format(systemUserSql.findSearchAccountSql(), Sql.sqlValue(searchBo.getAccount())));
		}
		systemUserAdapter.addWhereBetweenList(search, "t.create_time_", searchBo.getCreateStartTime(), searchBo.getCreateEndTime(), "yyyy-MM-dd HH:mm:ss");
		systemUserAdapter.addOrderBy(search, "change_time_", Sql.ORDER_BY_DESC);
		PageVo<SystemUserDataDo> page=systemUserAdapter.findPageList(search);//将Do转换为Vo
		PageVo<SystemUserPageVo> pageVo = this.convertPage(page, SystemUserPageVo.class);
		pageVo.forEach(new PageRowHandler<SystemUserPageVo>() {
			@Override
			public void handler(SystemUserPageVo rowData, int index) {
				rowData.setIdCardTypeName(cacheAdapter.findDictionaryValueByKey("idCardType", getLanguage(), rowData.getIdCardType()+""));
			}
		});;
		return pageVo;
	}
	
	@ApiMethod(value="查询会员分页数据", params=@ApiField("分页对象，包含分页信息及查询条件"), returns=@ApiField("包含查询数据的分页对象"))
	public PageVo<SystemDepartmentUserPageVo> findDepartmentPageList(SystemDepartmentUserPageBo searchBo){
		SystemUserPageDo search=this.convertPojo(searchBo, SystemUserPageDo.class);//将Bo转换为Do
		search.setFirstSize((search.getCurrPage()-1)*search.getPageSize());
		systemUserAdapter.addSelectColumn(search, systemUserSql.findAccountSql(), "account");
		systemUserAdapter.addSelectColumn(search, systemUserSql.findPhoneSql(), "phone");
		systemUserAdapter.addSelectColumn(search, systemUserSql.findEmailSql(), "email");
		systemUserAdapter.addSelectColumn(search, systemUserSql.findRoleNamesSql(), "roleNames");
		systemUserAdapter.addWhereIn(search, "t.id_", Sql.format(systemUserSql.findSearchDepartmentIdSql(), searchBo.getDepartmentId()));
		if(ObjectUtils.isNotEmpty(searchBo.getAccount())){
			systemUserAdapter.addWhereIn(search, "t.id_", Sql.format(systemUserSql.findSearchAccountSql(), Sql.sqlValue(searchBo.getAccount())));
		}
		systemUserAdapter.addWhereBetweenList(search, "t.create_time_", searchBo.getCreateStartTime(), searchBo.getCreateEndTime(), "yyyy-MM-dd HH:mm:ss");
		systemUserAdapter.addOrderBy(search, "change_time_", Sql.ORDER_BY_DESC);
		PageVo<SystemUserDataDo> page=systemUserAdapter.findPageList(search);//将Do转换为Vo
		PageVo<SystemDepartmentUserPageVo> pageVo = this.convertPage(page, SystemDepartmentUserPageVo.class);
		pageVo.forEach(new PageRowHandler<SystemDepartmentUserPageVo>() {
			@Override
			public void handler(SystemDepartmentUserPageVo rowData, int index) {
				rowData.setIdCardTypeName(cacheAdapter.findDictionaryValueByKey("idCardType", getLanguage(), rowData.getIdCardType()+""));
			}
		});;
		return pageVo;
	}
	
	@ApiMethod(value="查询会员详情", params=@ApiField("详情业务实体，包含id字段"), returns=@ApiField("会员详情数据"))
	public SystemUserViewVo view(SystemUserViewBo viewBo){
		SystemUserSingleDo search=this.convertPojo(viewBo, SystemUserSingleDo.class);
		systemUserAdapter.addSelectColumn(search, systemUserSql.findAccountSql(), "account");
		systemUserAdapter.addSelectColumn(search, systemUserSql.findPhoneSql(), "phone");
		systemUserAdapter.addSelectColumn(search, systemUserSql.findEmailSql(), "email");
		systemUserAdapter.addSelectColumn(search, systemUserSql.findRoleNamesSql(), "roleNames");
		systemUserAdapter.addSelectColumn(search, systemUserSql.findDepartmentJobUserIdsSql(), "departmentJobIds");
		systemUserAdapter.addSelectColumn(search, systemUserSql.findDepartmentJobUserNamesSql(), "departmentJobNames");
		SystemUserDataDo single=systemUserAdapter.findSingle(search);
		return this.convertPojo(single, SystemUserViewVo.class);//将Do转换为Vo
	}

	@SuppressWarnings("unchecked")
	@Transactional("systemTransactionManager")
	@OperatorLogger(type = OperatorTypeEnum.CREATE)
	@ApiMethod(value="创建会员", params=@ApiField("创建的业务实体"), returns=@ApiField("创建结果{0：未创建，1：已创建}"))
	public SystemUserCreateVo create(SystemUserCreateBo createBo){
		LoggerUtils.setModule(systemUserAdapter.getModule());//设置日志所属模块
		if(ObjectUtils.isNotEmpty(createBo.getDepartmentJobIds())) {
			createBo.setDepartmentJobIdList(JsonUtils.toJava(createBo.getDepartmentJobIds(), List.class));
		}
		validateAdapter.setAttribute("accountDb", systemUserAccountAdapter);
		validateAdapter.setAttribute("departmentDb", systemDepartmentAdapter);
		validateAdapter.setAttribute("departmentJobDb", systemDepartmentJobAdapter);
		validateAdapter.validate(systemUserAdapter.getModule(), "save", createBo, getUser(), systemUserAdapter);
		
		SystemUserInsertDo insert=this.convertPojo(createBo, SystemUserInsertDo.class);//将Bo转换为Do
		if(ObjectUtils.isNotEmpty(insert.getIdCardShow())) {
			insert.setIdCard(EncryptionUtils.md5Hex(insert.getIdCardShow()));
			insert.setIdCardShow(StringUtils.hiddenCenter(insert.getIdCardShow(), 4, 3));
		}
		insert.setPassword(EncryptionUtils.md5Hex(insert.getPassword()));
		int result=systemUserAdapter.save(insert, false);//保存客户基本信息
		LoggerUtils.setId(insert.getId());//创建日志需要设置数据id
		systemUserAccountAdapter.save(new SystemUserAccountInsertDo(insert.getId(), createBo.getAccount(), "no"), false);//保存登录账号
		if(ObjectUtils.isNotEmpty(createBo.getPhone())) {
			systemUserAccountAdapter.save(new SystemUserAccountInsertDo(insert.getId(), createBo.getPhone(), "phone"), false);//保存手机号
		}
		if(ObjectUtils.isNotEmpty(createBo.getEmail())) {
			systemUserAccountAdapter.save(new SystemUserAccountInsertDo(insert.getId(), createBo.getEmail(), "email"), false);//保存邮箱
		}
		if(ObjectUtils.isNotEmpty(createBo.getDepartmentJobIdList())) {
			for (List<Object> departmentJobId : createBo.getDepartmentJobIdList()) {
				SystemDepartmentUserInsertDo departmentUserInsert=new SystemDepartmentUserInsertDo();
				departmentUserInsert.setDepartmentId(Long.parseLong(departmentJobId.get(0).toString()));
				departmentUserInsert.setUserId(insert.getId());
				systemDepartmentUserAdapter.save(departmentUserInsert, false);
				if(departmentJobId.size()==2) {
					SystemDepartmentJobDataDo departmentJob = systemDepartmentJobAdapter.findByDepartmentIdAndJobId(Long.parseLong(departmentJobId.get(0).toString()), Long.parseLong(departmentJobId.get(1).toString()));
					SystemDepartmentJobUserInsertDo departmentJobUserInsert=new SystemDepartmentJobUserInsertDo();
					departmentJobUserInsert.setDepartmentJobId(departmentJob.getId());
					departmentJobUserInsert.setDepartmentUserId(departmentUserInsert.getId());
					systemDepartmentJobUserAdapter.save(departmentJobUserInsert, false);
				}
			}
		}
		return new SystemUserCreateVo(result);
	}
	
	@SuppressWarnings("unchecked")
	@Transactional("systemTransactionManager")
	@OperatorLogger(type = OperatorTypeEnum.UPDATE)
	@ApiMethod(value="更新会员", params=@ApiField("更新的业务实体"), returns=@ApiField("更新结果{0：未创建，1：已创建}"))
	public SystemUserUpdateVo update(SystemUserUpdateBo updateBo){
		LoggerUtils.setModule(systemUserAdapter.getModule());//设置日志所属模块
		SystemUserSingleDo search=new SystemUserSingleDo();
		search.setId(updateBo.getId());
		systemUserAdapter.addSelectColumn(search, systemUserSql.findAccountSql(), "account");
		systemUserAdapter.addSelectColumn(search, systemUserSql.findPhoneSql(), "phone");
		systemUserAdapter.addSelectColumn(search, systemUserSql.findEmailSql(), "email");
		systemUserAdapter.addSelectColumn(search, systemUserSql.findRoleNamesSql(), "roleNames");
		systemUserAdapter.addSelectColumn(search, systemUserSql.findDepartmentJobUserNamesSql(), "departmentJobNames");
		SystemUserDataDo currUser=systemUserAdapter.findSingle(search);
		LoggerUtils.setOriginalData(currUser);//设置日志原数据对象
		if(ObjectUtils.isNotEmpty(updateBo.getDepartmentJobIds())) {
			updateBo.setDepartmentJobIdList(JsonUtils.toJava(updateBo.getDepartmentJobIds(), List.class));
		}
		SystemUserUpdateDo update=this.convertPojo(updateBo, SystemUserUpdateDo.class);//将Bo转换为Do
		if(ObjectUtils.isNotEmpty(update.getIdCardShow())){
			if(update.getIdCardShow().contains("*")) {
				update.setIdCardShow(null);
			}else {
				update.setIdCard(EncryptionUtils.md5Hex(update.getIdCardShow()));
				update.setIdCardShow(StringUtils.hiddenCenter(update.getIdCardShow(), 4, 3));
			}
		}
		int result=systemUserAdapter.update(update, true);
		systemDepartmentJobUserAdapter.deleteByUserId(update.getId());
		systemDepartmentUserAdapter.deleteByUserId(update.getId());
		if(ObjectUtils.isNotEmpty(updateBo.getDepartmentJobIdList())) {
			for (List<Object> departmentJobId : updateBo.getDepartmentJobIdList()) {
				SystemDepartmentUserInsertDo departmentUserInsert=new SystemDepartmentUserInsertDo();
				departmentUserInsert.setDepartmentId(Long.parseLong(departmentJobId.get(0).toString()));
				departmentUserInsert.setUserId(update.getId());
				systemDepartmentUserAdapter.save(departmentUserInsert, false);
				if(departmentJobId.size()==2) {
					SystemDepartmentJobDataDo departmentJob = systemDepartmentJobAdapter.findByDepartmentIdAndJobId(Long.parseLong(departmentJobId.get(0).toString()), Long.parseLong(departmentJobId.get(1).toString()));
					SystemDepartmentJobUserInsertDo departmentJobUserInsert=new SystemDepartmentJobUserInsertDo();
					departmentJobUserInsert.setDepartmentJobId(departmentJob.getId());
					departmentJobUserInsert.setDepartmentUserId(departmentUserInsert.getId());
					systemDepartmentJobUserAdapter.save(departmentJobUserInsert, false);
				}
			}
		}
		return new SystemUserUpdateVo(result);
	}
	
	@OperatorLogger(type = OperatorTypeEnum.UPDATE)
	@ApiMethod(value="更新会员状态", params=@ApiField("更新的业务实体"), returns=@ApiField("更新结果{0：未更新，1：已更新}"))
	public SystemUserUpdateStatusVo updateStatus(SystemUserUpdateStatusBo updateBo){
		LoggerUtils.setModule(systemUserAdapter.getModule());//设置日志所属模块
		SystemUserDataDo view=systemUserAdapter.findById(updateBo.getId());
		LoggerUtils.setOriginalData(view);//设置日志原数据对象
		SystemUserUpdateDo update=this.convertPojo(updateBo, SystemUserUpdateDo.class);//将Bo转换为Do
		int result=systemUserAdapter.update(update, false);
		return new SystemUserUpdateStatusVo(result);
	}
	
	@Transactional("systemTransactionManager")
	@OperatorLogger(type = OperatorTypeEnum.UPDATE, pkFileName = "userId")
	@ApiMethod(value="更新授权", params=@ApiField("更新授权的业务实体"), returns=@ApiField("更新结果"))
	public SystemUserRoleUpdateVo updateAuthorize(SystemUserRoleUpdateListBo updateBo) {
		LoggerUtils.setModule(systemUserAdapter.getModule());//设置日志所属模块
		List<SystemUserRoleDataDo> currList = systemUserRoleAdapter.findByUserId(updateBo.getUserId(), AuthorityTypeEnum.OCCUPANT.getKey());
		LoggerUtils.setOriginalData(new SystemUserRoleUpdateListBo(this.convertPojoList(currList, SystemUserRoleUpdateBo.class)));		
		systemUserRoleAdapter.deleteByUserId(updateBo.getUserId(), AuthorityTypeEnum.OCCUPANT.getKey());
		List<SystemUserRoleInsertBatchItemDo> batchList=this.convertPojoList(updateBo.getList(), SystemUserRoleInsertBatchItemDo.class);
		if(ObjectUtils.isNotEmpty(batchList)) {
			for (SystemUserRoleInsertBatchItemDo item : batchList) {
				item.setUserId(updateBo.getUserId());
				item.setAuthorityType(AuthorityTypeEnum.OCCUPANT.getKey());
			}
			int result=systemUserRoleAdapter.saveBatch(new SystemUserRoleInsertBatchDo(batchList), false);
			return new SystemUserRoleUpdateVo(result);
		}
		return new SystemUserRoleUpdateVo(0);
	}
	
	@Transactional("systemTransactionManager")
	@OperatorLogger(type = OperatorTypeEnum.DELETE)
	@ApiMethod(value="删除会员", params=@ApiField("删除业务实体，包含id字段"), returns=@ApiField("删除结果{0：未创建，1：已创建}"))
	public SystemUserDeleteVo delete(SystemUserDeleteBo deleteBo){
		LoggerUtils.setModule(systemUserAdapter.getModule());//设置日志所属模块
		SystemUserDataDo user=systemUserAdapter.findById(deleteBo.getId());
		ExceptionUtils.empty(user, "delete.object.not.exists", "用户信息");
		SystemUserDeleteDo delete=this.convertPojo(deleteBo, SystemUserDeleteDo.class);//将Bo转换为Do
		systemDepartmentJobUserAdapter.deleteByUserId(deleteBo.getId());
		systemDepartmentUserAdapter.deleteByUserId(deleteBo.getId());
		systemUserRoleAdapter.deleteByUserId(deleteBo.getId(), null);
		systemUserAccountAdapter.deleteByUserId(deleteBo.getId());
		int result=systemUserAdapter.delete(delete);
		return new SystemUserDeleteVo(result);
	}
	
	@ApiMethod(value="查询用户授权角色列表", params=@ApiField("查询条件"), returns=@ApiField("授权角色列表"))
	public SystemUserAuthorizeRoleListVo findAuthorizeRoleList(SystemUserAuthorizeRoleListBo searchBo) {
		TokenUser user = this.getUser();	
		List<SystemRoleDataDo> roleList;
		SystemRoleSearchDo search=new SystemRoleSearchDo();
		if(user.getIsAdmin()!=1) {
			Sql sql=Sql.createSql();
			sql.addWhere(Sql.LOGIC_AND, "id_", Sql.COMPARE_IN, Sql.format(systemUserSql.findSearchRoleIdByUserIdSql(), user.getId()));
			search.setSql(sql);
		}
		roleList=systemRoleAdapter.findList(search);
		List<SystemUserAuthorizeRoleVo> resultList = this.convertPojoList(roleList, SystemUserAuthorizeRoleVo.class);
		List<SystemUserRoleDataDo> currList = systemUserRoleAdapter.findByUserId(searchBo.getUserId(), AuthorityTypeEnum.OCCUPANT.getKey());
		if(ObjectUtils.isNotEmpty(resultList) && ObjectUtils.isNotEmpty(currList)) {
			Set<Long> roleIdList=currList.stream().map(r -> r.getRoleId()).distinct().collect(Collectors.toSet());
			resultList.forEach(r -> {
				if(roleIdList.contains(r.getId())){
					r.setChecked(true);
				}else {
					r.setChecked(false);
				}
			});
		}
		return new SystemUserAuthorizeRoleListVo(resultList);
	}
	
	@SuppressWarnings("unchecked")
	@ApiMethod(value="查询部门/职位", params=@ApiField("查询条件"), returns=@ApiField("授权角色列表"))
	public SystemUserDepartmentJobTreeVo findDepartmentJobTree(SystemUserDepartmentJobTreeBo treeBo) {
		SystemDepartmentSearchDo search=new SystemDepartmentSearchDo();
        systemDepartmentAdapter.addOrderBy(search, "parent_id_", Sql.ORDER_BY_ASC);
        systemDepartmentAdapter.addOrderBy(search, "sort_", Sql.ORDER_BY_ASC);
        List<SystemDepartmentDataDo> list = systemDepartmentAdapter.findList(search);
        SystemUserDepartmentJobTreeVo root=new SystemUserDepartmentJobTreeVo("-1", "department", "部门树", true, false);
        root.setIcon(TreeIconEnum.ORGANIZATION.getKey());
        if(ObjectUtils.isNotEmpty(list)) {
        	List<SystemDepartmentDataDo> rootList=list.stream().filter(r -> r.getType().equals("headOffice") && ObjectUtils.isEmpty(r.getParentId())).collect(Collectors.toList());
        	if(ObjectUtils.isEmpty(rootList)){
        		return root;
        	}
        	SystemDepartmentJobSearchDo departmentJobsearch=new SystemDepartmentJobSearchDo();
        	systemDepartmentJobAdapter.addSelectColumn(departmentJobsearch, "j.id_", "jobId");
        	systemDepartmentJobAdapter.addSelectColumn(departmentJobsearch, "j.name_", "jobName");
        	systemDepartmentJobAdapter.addSelectColumn(departmentJobsearch, "d.id_", "departmentId");
        	systemDepartmentJobAdapter.addJoinTable(departmentJobsearch, "system_job_", "j", "t.job_code_=j.code_ and j.is_delete_=0");
        	systemDepartmentJobAdapter.addJoinTable(departmentJobsearch, "system_department_", "d", "t.department_code_=d.code_ and d.is_delete_=0");
        	systemDepartmentJobAdapter.addWhereInList(departmentJobsearch, "t.department_code_", list.stream().map(d -> d.getCode()).collect(Collectors.toList()));
        	List<SystemDepartmentJobDataDo> jobList = systemDepartmentJobAdapter.findList(departmentJobsearch);
        	List<List<Object>> checkedList=new ArrayList<>();
        	if(ObjectUtils.isNotEmpty(treeBo.getCheckedJson())) {
        		checkedList=JsonUtils.toJava(treeBo.getCheckedJson(), List.class);
        	}
        	if(rootList.size()==1) {
        		root.setId(rootList.get(0).getId()+"");
        		root.setTitle(rootList.get(0).getName());
        		systemDepartmentJobAdapter.parseDepartmentJobToTree(list, jobList, root, checkedList);
        	} else {
        		List<SystemUserDepartmentJobTreeVo> childList=new ArrayList<SystemUserDepartmentJobTreeVo>();
        		SystemUserDepartmentJobTreeVo childNode;
        		for (SystemDepartmentDataDo department : rootList) {
        			childNode=new SystemUserDepartmentJobTreeVo(department.getId()+"", "department", department.getName());
        			childNode.setSpread(true);
        			if(checkedList.stream().filter(s -> s.size()==1 && Long.parseLong(s.get(0).toString())==department.getId()).findAny().isPresent()) {
        				childNode.setChecked(true);
        			}
        			childList.add(childNode);
        			systemDepartmentJobAdapter.parseDepartmentJobToTree(list, jobList, childNode, checkedList);
        			systemDepartmentJobAdapter.parseJobToTree(jobList, childNode, checkedList);
				}
        		root.setChildren(childList);
        	}
        }
		return root;
	}
}
